package com.threadpool;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

public class DefaultThreadPool<Job extends Runnable> implements ThreadPool<Job> {
	// 线程池最大限制数
	private static final int MAX_WORKER_NUMBERS = 10;
	// 线程池默认的数量
	private static final int DEFAULT_WORKER_NUMBERS = 5;
	// 线程池最小的数量
	private static final int MIN_WORKER_NUMBERS = 1;
	// 这是一个工作列表，将会向里面插入工作
	private final LinkedList<Job> jobs = new LinkedList<Job>();
	// 工作者列表
	private List<Worker> workers = new LinkedList<Worker>();
	// 工作者线程的数量
	private int workerNum = DEFAULT_WORKER_NUMBERS;
	// 线程编号生成
	private AtomicLong threadNum = new AtomicLong();

	public DefaultThreadPool() {
		initializeWokers(DEFAULT_WORKER_NUMBERS);
	}

	public DefaultThreadPool(int num) {
		workerNum = num > MAX_WORKER_NUMBERS ? MAX_WORKER_NUMBERS
				: num < MIN_WORKER_NUMBERS ? MIN_WORKER_NUMBERS : num;
		initializeWokers(workerNum);
	}

	public void execute(Job job) {
		if (job != null) {
			// 添加一个工作，然后进行通知
			synchronized (jobs) {
				jobs.addLast(job);
				jobs.notify();
			}
		}
	}

	public void shutdown() {
		// 如果还有任务没执行完成，就先睡会吧
		while (!jobs.isEmpty()) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (Worker worker : workers) {
			worker.shutdown();
			worker = null;
		}
		workers = null;
		// for (int i = 0; i < workers.size(); i++) {
		// workers.get(i).shutdown();
		// }
		// for (int i = 0; i < workers.size() + 1; i++) {
		// workers.get(i) = null;
		// }
		jobs.clear();// 清空任务队列
	}

	public void addWorkers(int num) {
		synchronized (jobs) {
			// 限制新增的Worker数量不能超过最大值
			if (num + this.workerNum > MAX_WORKER_NUMBERS) {
				num = MAX_WORKER_NUMBERS - this.workerNum;
			}
			initializeWokers(num);
			this.workerNum += num;
		}
	}

	public void removeWorker(int num) {
		synchronized (jobs) {
			if (num >= this.workerNum) {
				throw new IllegalArgumentException("beyond workNum");
			}
			// 按照给定的数量停止Worker
			int count = 0;
			while (count < num) {
				Worker worker = workers.get(count);
				if (workers.remove(worker)) {
					worker.shutdown();
					count++;
				}
			}
			this.workerNum -= count;
		}
	}

	public int getJobSize() {
		return jobs.size();
	}

	// 初始化线程工作者
	private void initializeWokers(int num) {
		for (int i = 0; i < num; i++) {
			Worker worker = new Worker();
			workers.add(worker);
			Thread thread = new Thread(worker, "ThreadPool-Worker-"
					+ threadNum.incrementAndGet());
			thread.start();
		}
	}

	// 工作者，负责消费任务
	class Worker implements Runnable {
		// 该工作线程是否有效，用于结束该工作线程
		private volatile boolean running = true;

		/*
		 * 关键所在啊，如果任务队列不空，则取出任务执行，若任务队列空，则等待
		 */
		@Override
		public void run() {
			Runnable job = null;
			while (running) {
				synchronized (jobs) {
					// 线程还在运行
					// 并且，如果工作者列表是空的，那么就wait
					while (running && jobs.isEmpty()) { // 队列为空
						try {
							jobs.wait(20);
						} catch (InterruptedException ex) {
							// 感知到外部对WorkerThread的中断操作，返回
							Thread.currentThread().interrupt();
							return;
						}
					}
					if (!jobs.isEmpty())
						job = jobs.remove(0);// 取出任务
				}
				if (job != null) {
					job.run(); // 执行任务
				}
				// 释放资源
				job = null;
			}
		}

		// 停止工作，让该线程自然执行完run方法，自然结束
		public void shutdown() {
			running = false;
		}
	}

	@Override
	public int getThreadSize() {

		return workerNum;
	}
}